﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace Ordinaire.Tool
{
    /// <summary>
    /// Provides static functions to serialise an object to xml text and deserialise xml text to a specified object.
    /// </summary>
    public class XmlSerializerHelper : XmlSerializer
    {
        /// <summary>
        /// Deserialises a specified text and returns new instance of specified type.
        /// </summary>
        /// <typeparam name="T">type to deserialize to</typeparam>
        /// <param name="text">text to deserialize</param>
        /// <returns>new instance of specified type</returns>
        public static T Deserialize<T>(string text)
        {
            MemoryStream  memory     = new MemoryStream(Encoding.UTF8.GetBytes(text));
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            return (T) serializer.Deserialize(memory);
        }

        /// <summary>
        /// Serialises the specified object into an Xml string.
        /// </summary>
        /// <param name="obj">object to serialise</param>
        /// <returns>serialised Xml string</returns>
        public static string Serialize(Object obj)
        {
            MemoryStream memory = new MemoryStream();
            StreamWriter writer = new StreamWriter(memory, Encoding.UTF8);

            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            XmlSerializerNamespaces xs = new XmlSerializerNamespaces();
            // Get rid of Xml namespaces
            xs.Add("", "");
            serializer.Serialize(writer, obj, xs);

            memory.Position = 0;
            StreamReader reader1 = new StreamReader(memory, Encoding.UTF8);
            string serialisedText = reader1.ReadToEnd();
            memory.Close();

            return serialisedText;
        }
    }
}
